<?php
/**
 * XCache缓存引擎
 *
 * @package if
 * @subpackage module.cache
 * @since 1.1.0
 */
class IXcacheEngine extends IAbstractCacheEngine {
	private $settings = array();
	
	function init(array $settings = null) {
		if (is_array($settings)) {
			$this->settings = $settings;
		}
		$enabled = (bool)extension_loaded("xcache");
		if (!$enabled) {
			throw new ICacheException("xcache extension must be loaded in php.ini", 0x100069);
		}
		
		//settings
		$_setting = o("@cache.xcache");
		if ($settings) {
			$_setting = array_merge($_setting, $settings);
		}
		$this->settings = $_setting;
	}
	
	function clear($expired = false) {
		if (isset($this->settings["xcache.admin.user"])) {
			$_SERVER["PHP_AUTH_USER"] = $this->settings["xcache.admin.user"];
		}
		if (isset($this->settings["xcache.admin.pass"])) {
			$_SERVER["PHP_AUTH_PW"] = $this->settings["xcache.admin.pass"];
		}
		$result = true;
		if (!$expired) {
			for ($i = 0, $max = xcache_count(XC_TYPE_VAR); $i < $max; $i++) {
			if (!xcache_clear_cache(XC_TYPE_VAR, $i)) {
					$result = false;
					break;
				}
			}
			return $result;
		}
		return true;
	}
	
	function delete($key) {
		return xcache_unset($key);
	}
	
	function _entry($key) {
		if (!xcache_isset($key)) {
			return null;
		}
		$array = xcache_get($key);
		if (!is_array($array)) {
			if ($array) {
				$this->delete($key);
			}
			return null;
		}
		
		$entry = new ICacheEntry($array);
		$entry->setEngine($this);
		if ($entry->expired()) {
			$this->delete($key);
			return null;
		}
		return $entry;
	}
	
	function _writeEntry(ICacheEntry $entry) {
		return xcache_set($entry->key(), $array, $entry->ttl());
	}
}

?>